import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

// 阻塞队列：在普通循环队列的基础上，增加阻塞的功能，让它变成阻塞队列。然后使用自定义阻塞队列实现生产者消费者模型。
class MyBlockingQueue {
    private int[] items = new int[100];
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    public void put(int val) throws InterruptedException {
        synchronized (this){
            while (size == items.length){
                // 队列满时wait，等待先take()元素出队后才能继续执行入队元素
                this.wait();
            }
            items[tail] = val;
            tail++;
            size++;
            // tail = tail % items.length;
            if(tail == items.length){ // 上面的取模操作和这一步操作功能一样，但是这里的比较比取模效率高，且代码可读性更高。
                tail = 0;
            }
            // 唤醒take中队空时的wait操作
            this.notify();
        }
    }
    public Integer take() throws InterruptedException {
        int result = 0;
        synchronized (this) {
            while (size == 0) {
                // 队列空时wait，等待先put()入队元素后才能继续执行出队元素
                this.wait();
            }
            result = items[head];
            head++;
            size--;
            if (head == items.length) {
                head = 0;
            }
            // 唤醒put中队满时的wait操作
            this.notify();
        }
        return result;
    }
}

public class Main {
    public static void main(String[] args){
        MyBlockingQueue queue = new MyBlockingQueue();
        // 消费者
        Thread costumer = new Thread(()->{
            while (true){
                try {
                    int result = queue.take();
                    System.out.println("消费元素：" + result);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 加sleep便于观察运行时具体情况
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        // 生产者
        Thread producer = new Thread(()->{
            int count = 0;
            while (true) {
                try {
                    count++;
                    queue.put(count);
                    System.out.println("生产元素：" + count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();
        costumer.start();
        System.out.println("Ok");
    }
}
